package com.sqly.doc.menu.qianyue;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CheckBoxAdapter;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.pojo.Team;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.LvHeightUtil;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * 选择用户界面
 * Created by Administrator on 2017-11-14.
 */

public class choose_servicepack extends MyBaseActivity {


    XListView listView;
    ZLoadingDialog dialog;//加载动画
    Context con;
    private int pageNum1 = 1;// 无关键字页数
    EditText key;
    TextView title, uname, fwnrid, fwnrname;
    private ImageView cx;
    List<ServicePackage> list  = new ArrayList<ServicePackage>();//医疗团队成员

    @Override
    protected void initUI() {
        setContentView(R.layout.servicepack_choose);
        cx = (ImageView) findViewById(R.id.cx);
        cx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum1 = 1;
                getSpData();
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        fwnrid = (TextView) findViewById(R.id.fwnridStr);
        fwnrname = (TextView) findViewById(R.id.fwnrnameStr);
//        fwnrid.setText(getIntent().getExtras().getString("oldfwnrids"));
//        fwnrid.setText(getIntent().getExtras().getString("oldfwnrnames"));
        title.setText("选择服务包");
        uname.setText("确认选择");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(con, getIntent().getStringExtra("cname").getClass());
                intent.putExtra("fwnrnames", fwnrname.getText().toString());
                intent.putExtra("fwnrids", fwnrid.getText().toString());
                setResult(12, intent);
                finish();
            }
        });
        con = choose_servicepack.this;
        key = (EditText) findViewById(R.id.key);
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色

    }

    @Override
    protected void initData() {
        if (NetWorkUtils.isNetworkConnected(con)) {//网络没有连接
            getSpData();
        }else{
            MyToastUtil.ShowToast(con, "获取错误");
        }
    }

    @Override
    protected void initListener() {

    }

    //更新居民信息
    //网络请求居民信息
    public void getSpData() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page",  pageNum1 + "");
        ps.add("pageSize","10");
        if (key.getText().toString().length() != 0) {
            ps.add("XINGMING", key.getText().toString());
        }
        UserClient.get(HttpUrl.GetSpByYsOrJmPagelst, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    listView.setPullLoadEnable(pageNum1, Integer.parseInt(null ==ret.getTotalPage() || "".equals(ret.getTotalPage()) ? "0" : ret.getTotalPage()));

                    if (pageNum1 == 1)
                        list = new ArrayList<ServicePackage>();
                    List<ServicePackage> ll = JSON.parseArray(ret.getList(), ServicePackage.class);
                    JSONArray js = JSON.parseArray(ret.getList());
                    for (int i = 0; i < js.size(); i++) {
                        JSONObject j = js.getJSONObject(i);
                        ll.get(i).setSid(j.getString("id"));
                    }
                    for (int i = 0; i < ll.size(); i++) {
                        list.add(ll.get(i));
                    }

                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getSpData();
                        }

                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getSpData();
                        }
                    });
                    final Map<String, String> mapTemp = new HashMap<String, String>();
                    final CheckBoxAdapter myAdapter = new CheckBoxAdapter(con);
                    myAdapter.setDatas(list);
                    listView.setAdapter(myAdapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        int currentNum = -1;
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            ServicePackage sp = list.get(position -1);
                            if(sp.isChecked()){
                                sp.setChecked(false);
                                if(null != mapTemp.get(sp.getSid())) {
                                    mapTemp.remove(sp.getSid());
                                }
                            }else {
                                sp.setChecked(true);
                                mapTemp.put(sp.getSid(), sp.getName());
                            }
                            String idKey = "-1", nameValue ="";
                            Iterator<Map.Entry<String,String>> iter = mapTemp.entrySet().iterator();
                            String fwnrids = "";
                            String fwnrnames = "";
                            while(iter.hasNext()){
                                Map.Entry<String,String> entry = iter.next();
                                idKey = entry.getKey(); nameValue = entry.getValue();
                                fwnrids = idKey+","+fwnrids;
                                fwnrnames =  nameValue+","+fwnrnames;
                            }
                            if(null != fwnrids && fwnrids.length()>1 && fwnrids.endsWith(",")){
                                fwnrids = fwnrids.substring(0, fwnrids.length()-1);
                            }
                            if(null != fwnrnames && fwnrnames.length()>1 && fwnrnames.endsWith(",")){
                                fwnrnames = fwnrnames.substring(0, fwnrnames.length()-1);
                            }
                            fwnrid.setText(fwnrids);
                            fwnrname.setText(fwnrnames);
                            myAdapter.notifyDataSetChanged();//刷新adapter
                        }
                    });
                    LvHeightUtil.setListViewHeightBasedOnChildren(listView);
                }
            }
        });


    }
}
